package com.zy.dao.impl;

import com.zy.dao.GetOrdersDao;
import com.zy.entity.Order;
import com.zy.utils.JdbcUtil;
import com.zy.service.FindUserByIdService;
import com.zy.service.impl.FindUserByIdServiceImpl;
import com.zy.entity.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class GetOrdersDaoImpl implements GetOrdersDao {
    @Override
    public List<Order> getOrders(int offset, int limit) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT o.id, o.payment_amount, o.payment_time, o.user_id, u.username FROM tb_order o JOIN tb_user u ON o.user_id = u.id LIMIT ? OFFSET ?";
        try (Connection conn = JdbcUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, limit);
            pstmt.setInt(2, offset);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                FindUserByIdService findUserByIdService = new FindUserByIdServiceImpl();
                User user = findUserByIdService.findUserById(rs.getInt("user_id"));
                String username = user != null ? user.getUserName() : "Unknown";
                Order order = new Order(rs.getInt("id"), String.valueOf(rs.getDouble("payment_amount")), rs.getTimestamp("payment_time"), rs.getInt("user_id"), username);
                orders.add(order);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }
} 